﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using DB.DbObjects;
using CodeTools.Common;
using PdmModels;



namespace CodeTools
{
    public partial class ContentForm : DockContentForm
    {
        public ContentForm()
        {
            InitializeComponent();
        }



        public DataTable columnsdt = null;

        public IniFileHelp ini = new IniFileHelp();

        public CodeType codeType;
        private void ContentForm_Load(object sender, EventArgs e)
        {
            InitGrid();
            List<string> lstEnums = CodeType.简单三层.GetListEnums();
            tplComboBox.DataSource = lstEnums;
            txtClassName.Text = TableName;
        }

        private void InitGrid()
        {
            IDbObject dbObject = null;
            if (ConnectionModel.DbType.Equals(DB.DbObjects.DatabaseType.SqlServer.ToString()))
            {
                dbObject = new DB.DbObjects.SQL2000.DbObject(ConnectionModel.ConnectionString);
            }
            else if (ConnectionModel.DbType.Equals(DB.DbObjects.DatabaseType.SqlServer9.ToString()))
            {
                dbObject = new DB.DbObjects.SQL2005.DbObject(ConnectionModel.ConnectionString);
            }
            else if (ConnectionModel.DbType.Equals(DB.DbObjects.DatabaseType.MsAccess.ToString()))
            {
                dbObject = new DB.DbObjects.OleDb.DbObject(ConnectionModel.ConnectionString);
            }
            else if (ConnectionModel.DbType.Equals(DB.DbObjects.DatabaseType.Oracle.ToString()))
            {
                dbObject = new DB.DbObjects.Oracle.DbObject(ConnectionModel.ConnectionString);
            }
            else if (ConnectionModel.DbType.Equals(DB.DbObjects.DatabaseType.Sqlite3.ToString()))
            {
                dbObject = new DB.DbObjects.SQLite.DbObject(ConnectionModel.ConnectionString);
            }
            else if (ConnectionModel.DbType.Equals(DB.DbObjects.DatabaseType.MySql.ToString()))
            {
                dbObject = new DB.DbObjects.MySQL.DbObject(ConnectionModel.ConnectionString);
            }
            else
            {
                MessageBox.Show("未知数据库类型!");
                return;
            }
            columnsdt = dbObject.GetColumnInfoList(DatabaseName, TableName);
            gridColumns.DataSource = columnsdt;

            DataTable primarykeydt = dbObject.GetKeyName(DatabaseName, TableName);
        }


        private void InitConfig()
        {
            txtClassName.Text = TableName.Trim().Replace(' ', '_');
            txtProjName.Text = ini.GetString(DatabaseName, "ProjName", string.Empty);
        }


        private void BtnUpdateFieldDesc_Click(object sender, EventArgs e)
        {
            int rowCount = gridColumns.Rows.Count;
            for (int j = 0; j < rowCount; j++)
            {
                object columnName = gridColumns.Rows[j].Cells["columnName"].Value ?? string.Empty;
                object deText = gridColumns.Rows[j].Cells["DeText"].Value ?? string.Empty;

                //---- For table
                //EXECUTE sp_addextendedproperty N'MS_Description', '描述内容', N'user', N'dbo', N'table', N'表名', NULL, NULL 
                //---- For column
                //EXECUTE sp_addextendedproperty N'MS_Description', '描述内容', N'user', N'dbo', N'table', N'表名', N'column', N'字段名'

				//comment on table OB_CALL_DATE_LOG is ‘该表是话单信息表’
				//comment on columm OB_CALL_DATE_LOG.PROJECT_ID is ‘项目标识’
				
				//ALTER TABLE `student` COMMENT '学生表2.0';
				//ALTER TABLE `student` MODIFY COLUMN `id` COMMENT '学号';
				
				

            }
        }


        private void cbToupperFrstword_CheckedChanged(object sender, EventArgs e)
        {
            txtClassName.Text = TableName;
            if (cbToupperFrstword.Checked)
            {
                txtClassName.Text = txtClassName.Text.ToUpperFirstword();
            }
        }

        /// <summary>
        /// 代码生成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBuilder_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtProjName.Text))
            {
                MessageBox.Show("项目名称不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2);
                txtProjName.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txtClassName.Text))
            {
                MessageBox.Show("类名不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2);
                txtClassName.Focus();
                return;
            }

            if (Ckd_Lbx.CheckedItems.Count <= 0)
            {
                MessageBox.Show("代码层至少为1个!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2);
                Ckd_Lbx.Focus();
                return;
            }

            List<Model.ColumnInfo> columns = Utils.GetColumnInfos(columnsdt);

            foreach (Model.ColumnInfo col in columns)
            {

                col.IsPK = false;

                //foreach (object o in cbPrimarykey.Items)
                //{
                //    if (col.ColumnName.Equals(o.ToString()))
                //    {
                //        col.IsPK = true;
                //        break;
                //    }
                //}
            }


            var lstSelItem = Ckd_Lbx.CheckedItems;

            foreach (var selItem in lstSelItem)
            {
                tabControl1.TabPages.Add(selItem.ToString(), selItem.ToString(), 1);
            }


            //EntityBuilder builder = new EntityBuilder(TableName, txtnamespace.Text, txtClassName.Text, columns, IsView, cbToupperFrstword.Checked, ConnectionModel.DbType);

            //txtContent.Text = builder.Builder(tplContent.Text);

            tabControl1.SelectedIndex = 1;






        }


        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveEntity.FileName = txtClassName.Text;
            saveEntity.Filter = "CS 文件|*.cs";

            if (saveEntity.ShowDialog() == DialogResult.OK)
            {
                using (StreamWriter sw = new StreamWriter(saveEntity.FileName, false, Encoding.UTF8))
                {
                    sw.Write(txtContent.Text);
                    sw.Close();
                }
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ((sender as TabControl).SelectedTab.Text == "生成代码")
            {
                btnBuilder_Click(null, null);
            }
        }

        private void tplComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Ckd_Lbx.Items.Clear();

            string codeType = tplComboBox.SelectedValue.ToString();

            if (codeType == CodeType.简单三层.ToString())
            {
                Ckd_Lbx.Items.Add("Model");
                Ckd_Lbx.Items.Add("BLL");
                Ckd_Lbx.Items.Add("DAL");
            }
            //else if (codeType == CodeType.简单三层.ToString())
            //{
            //    Ckd_Lbx.Items.Add("Model");
            //    Ckd_Lbx.Items.Add("BLL");
            //    Ckd_Lbx.Items.Add("DAL");   
            //    Ckd_Lbx.Items.Add("IBLL");
            //    Ckd_Lbx.Items.Add("IDAL");
            //}
            else if (codeType == CodeType.WCF简单三层.ToString())
            {
                Ckd_Lbx.Items.Add("Model");
                Ckd_Lbx.Items.Add("BLL");
                Ckd_Lbx.Items.Add("DAL");

                Ckd_Lbx.Items.Add("WCF");
            }
            else if (codeType == CodeType.WCF工厂三层.ToString())
            {
                Ckd_Lbx.Items.Add("Model");
                Ckd_Lbx.Items.Add("BLL");
                Ckd_Lbx.Items.Add("DAL");

                Ckd_Lbx.Items.Add("IBLL");
                Ckd_Lbx.Items.Add("IDAL");
                Ckd_Lbx.Items.Add("WCF");
            }

        }

        private void Ckd_Lbx_SelectedIndexChanged(object sender, EventArgs e)
        {
            CheckedListBox cklbx = (sender as CheckedListBox);
            if (cklbx != null)
            {
                int index = cklbx.SelectedIndex;

                CheckState ckState = cklbx.GetItemCheckState(index);

                CheckState setState = (ckState == CheckState.Checked) ? CheckState.Unchecked : CheckState.Checked;

                cklbx.SetItemCheckState(index, setState);
            }
        }

        private void BtnBrowPdm_Click(object sender, EventArgs e)
        {
            OpenFileDialog opfiledia = new OpenFileDialog();
            opfiledia.Filter = "";

            var openFileDialog = new OpenFileDialog
            {
                InitialDirectory = null,
                Filter = "(*.pdm)|*.pdm",
                RestoreDirectory = true
            };
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtPDM.Text = openFileDialog.FileName;

                UpdateGrid(txtPDM.Text);
            }
        }

        private void UpdateGrid(string pdmPath)
        {
            var pdmReader = new PdmReader();
            var lstTbl = pdmReader.ReadFromFile(pdmPath).Tables;
            TableInfo tabInfo = lstTbl.FirstOrDefault(t => t.Code.Equals(TableName, StringComparison.OrdinalIgnoreCase));
            if (tabInfo != null)
            {
                int rowCount = gridColumns.Rows.Count;
                for (int j = 0; j < rowCount; j++)
                {
                    object colName = gridColumns.Rows[j].Cells["columnName"].Value ?? string.Empty;
                    ColumnInfo colInfo = tabInfo.Columns.FirstOrDefault(t => t.Code.Equals(colName.ToString(), StringComparison.OrdinalIgnoreCase));
                    if (colInfo != null && string.IsNullOrEmpty(colInfo.Description))
                    {
                        gridColumns.Rows[j].Cells["detext"].Value = colInfo.Name ?? colInfo.Description ?? string.Empty;
                    }
                }
            }
        }




    }
}
